要測試 TextField 的 binding,先建立一個 MemoInputData 並讓這個物件 conform ObservableObject
step1: 建立 MemoInputData
import Foundation
class MemoInputData: ObservableObject {
}
step2: 在 MemoInputView 加上 MemoInputData
/// MemoInputView.swift
struct MemoInputView: View {
@State var inputedText: String = ""
@StateObject var data: MemoInputData
preview 也要改
struct MemoInputView_Previews: PreviewProvider {
static let data: MemoInputData = .init()
static var previews: some View {
MemoInputView(data: data)
}
}
step3: TextField 的 binding 需變更
struct MemoInputView: View {
@StateObject var data: MemoInputData
var displayText: String {
if data.inputedString.isEmpty {
return "請輸入文字"
} else {
return "你輸入的是: \(data.inputedString)"
}
}
var body: some View {
VStack {
Text(displayText)
TextField("請輸入交易心得", text: $data.inputedString)
}
.padding()
}
}
step4: Unit testing 並測試是否通過測試
func testMemoInputViewStart() throws {
let expect = "請輸入文字"
/// MemoInputView 裡面裝載了 vStack, 而 Text 在 0 個位置
let string = try sut.inspect().vStack().text(0).string()
XCTAssertEqual(expect, string)
}
func testMemoInputTextWithDummy() throws {
let dummyText = "foo"
let expect = "你輸入的是: foo"
try sut.inspect().vStack().textField(1).setInput(dummyText)
let string = try sut.inspect().vStack().text(0).string()
XCTAssertEqual(string, expect)
}
這樣就可以去測試 TextField 和 UI 元件的交互行為